package com.mihong.instance1;

import java.util.ArrayList;
import java.util.List;

import com.mihong.entity.Message;
import com.mihong.handler.Handler;
import com.mihong.util.CRC16Util;
import com.mihong.util.HexUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	//应答数据帧
	private List<byte[]> frames = new ArrayList();
	
	/**
     * 	向网关发送数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("网关与服务端通道-开启：" + ctx.channel().localAddress() + "channelActive");
        
        for(byte[] frame : frames) {
        	ctx.writeAndFlush(Unpooled.copiedBuffer(frame));
        	System.out.println(ctx.channel().localAddress()+":\n发送数据："+HexUtil.bytesToHexString(frame));
        	System.out.println("------------------------------");
        }
    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端通道-关闭：" + ctx.channel().localAddress() + "channelInactive");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("读取通道信息..");
        
        ByteBuf dataBuf = msg.readBytes(msg.readableBytes()-Message.BYTE_CRC-Message.BYTE_FRAME_END);
        
        //获取crc码
        String crc = ByteBufUtil.hexDump(msg.readBytes(Message.BYTE_CRC));
        
        //校验数据
        String crc16_ccitt = CRC16Util.CRC16_ccitt(ByteBufUtil.getBytes(dataBuf));
        
        //数据
        String dataStr = ByteBufUtil.hexDump(dataBuf);
        
        System.out.println("------------------------------");
        System.out.println(ctx.channel().localAddress()+"\n接收数据："+dataStr);
        
        //数据处理
        if(crc.equalsIgnoreCase(crc16_ccitt)) {
        	 //接收成功
        	frames = new Handler().handler(dataStr,Message.CHECK_SUCCESS);
        	
        }else {
        	//接收失败
        	frames = new Handler().handler(dataStr,Message.CHECK_FAILURE);
        } 
        channelActive(ctx);
        msg.retain();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常退出:" + cause.getMessage());
    }
    
   
    
}
